<template>
  <div class="warehouseManagement" style="min-width: 1200px">
    <modules-title title-name="库存管理">
      <template slot="btn">
        <el-button class="border-btn" plain @click="exportDrug">导出</el-button>
      </template>
    </modules-title>
    <div class="main" style="min-width: 1200px">
      <div class="searchBar">
        <el-form inline>
          <el-form-item label="药品检索">
            <!--   <el-input
              @keyup.enter.native="getWarehouseListData(form)"

                  clearable
                  class="inline-input"
                  v-model="form.key"
                  placeholder="名称/厂家/条码"

              ></el-input> -->
            <el-autocomplete
              :popper-append-to-body="false"
              clearable
              @focus="inputLenvo"
              @input="inputLenvo"
              @select="changeLenvo"
              class="inline-input"
              v-model="form.key"
              :fetch-suggestions="
                (queryString, cb) => {
                  querySearch(queryString, cb, 'product_name');
                }
              "
              @keyup.enter.native="getWarehouseListData(form)"
              placeholder="名称/厂家/条码"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="药品类型">
            <el-select
              @change="onChange1"
              v-model="form.category_id"
              placeholder="请选择药品类型"
            >
              <el-option
                v-for="item in optionsCategory"
                :key="item.ID"
                :label="item.category_name"
                :value="item.ID"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="药品状态">
            <el-select v-model="form.status" placeholder="请选择" @change="onChange">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-checkbox v-model="check" @change="getWarehouseListData(form)"
              >含空库存</el-checkbox
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="main-btn"
              @click="getWarehouseListData(form)"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-form-item>
              <el-button type="primary" class="main-btn" @click="resetForm"
                >重置
              </el-button>
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div class="table">
        <el-table
          :data="tableData"
          border
          :header-cell-style="{
            backgroundColor: '#F5F5F5',
            color: '#333333',
            fontFamily: 'MicrosoftYaHeiUI',
            fontSize: '14px',
            fontWeight: 900
          }"
        >
          <el-table-column prop="product_name" label="药品名称" align="center">
          </el-table-column>

          <el-table-column prop="pack" label="规格包装" align="center">
          </el-table-column>
          <el-table-column prop="production" label="生产厂家" align="center">
          </el-table-column>

          <el-table-column prop="category_name" label="产品类型" align="center">
          </el-table-column>
          <el-table-column prop="price" label="处方价" align="center">
            <template slot-scope="scope">
              <div class="price">{{ scope.row.price }}元</div>
            </template>
          </el-table-column>
          <el-table-column
            label="批次"
            align="center"
            prop="batch_no"
          ></el-table-column>

          <el-table-column prop="number" label="批次库存" align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.number + scope.row.piece_unit }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <div class="options">
                <el-button
                  type="text"
                  class="button"
                  @click="editDrugs(scope.row.id)"
                  >编辑
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="form.pager.number"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="form.pager.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import modulesTitle from "@/components/modulesTitle.vue";

import {
  getWarehouseList,
  deleteDrugsData,
  getDrugsCategory,
  exportDownload,
  getCentralList
} from "@/api/drugsManagement.js";

export default {
  components: { modulesTitle },
  name: "warehouseManagement",

  data() {
    return {
      inputAdv: [],
      total: 0,
      optionsCategory: [],
      form: {
        contain_empty: 0,
        key: "",
        status: -1,
        category_id: 0,
        pager: {
          number: 1,
          size: 10
        }
      },
      check: false,

      value: "",
      input2: "",
      statusOptions: [
        { label: "全部", value: -1 },
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 }
      ],

      tableData: [{ product_status: 0 }]
    };
  },
  created() {
    this.getDrugsCategoryData();
    this.$emit("getMessage", "drugInformationManagement");
    this.getWarehouseListData(this.form);
  },
  methods: {
    onChange(val) {
      this.form.status = val;
      this.form.pager.number = 1;
      this.getWarehouseListData(this.form);
    },
    onChange1(val) {
      this.form.category_id = val;
      this.form.pager.number = 1;
      this.getWarehouseListData(this.form);
    },
    resetForm() {
      this.form = {
        contain_empty: 0,
        key: "",
        status: -1,
        category_id: 0,
        pager: {
          number: 1,
          size: 10
        }
      };
      this.getWarehouseListData(this.form);
      this.check = false;
    },
    changeLenvo() {
      this.getWarehouseListData(this.form);
    },
    inputLenvo() {
      if (this.form.key != "") {
        getCentralList({ prefix: this.form.key, size: 10 }).then(res => {
          console.log(res.data);
          this.inputAdv = [];
          if (
            res.code == 200 &&
            res.data.self == true &&
            res.data.ElasticProduct != []
          ) {
            this.inputAdv = res.data.ElasticProduct;
            this.inputAdv.forEach(item => {
              item.value = item.product_name;
            });
          }
        });
      }
    },
    querySearch(queryString, cb, val) {
      let restaurants = this.inputAdv;
      console.log(restaurants);

      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;

      //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      console.log("22222222");
      console.log(results);
      if (results != []) {
        results = this.filterData(results);
      }

      cb(results);
    },
    filterData(arr) {
      let newArr = [];
      let bool = true;
      arr.forEach(item => {
        bool = true;
        if (newArr != []) {
          newArr.every(itm => {
            if (itm.product_name == item.product_name) {
              bool = false;
            }
            return itm.product_name != item.product_name;
          });
          if (bool == true) {
            newArr.push(item);
          }
        } else {
          newArr.push(item);
        }
      });
      console.log(newArr);

      return newArr;
    },

    createFilter(queryString) {
      return restaurant => {
        // return 1;
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
          restaurant.name_pinyin
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    //导出
    async exportDrug() {
      // return  this.$message('暂不可用')
      const res = await exportDownload();
      const link = document.createElement("a");
      let blob = new Blob([res], {
        type:
          "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      console.log(sessionStorage.getItem("Content-Disposition"));
      link.download = "库存列表.xlsx";

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleSizeChange(val) {
      this.form.pager.size = val;
      this.getWarehouseListData(this.form);
    },
    handleCurrentChange(val) {
      this.form.pager.number = val;
      this.getWarehouseListData(this.form);
    },
    getDrugsCategoryData() {
      getDrugsCategory().then(res => {
        this.optionsCategory = res.data;
      });
    },

    editDrugs(id) {
      /* this.$router.push({
            name: 'newDrugs',
            params: {
                id: id
            }
        }) */
      /* this.$router.push('/drugsManagement/pushWarehouse/storageLog') */
      this.$router.push({
        path: "/drugsManagement/warehouseManagement/newEditWarehouse",
        query: {
          id: id
        }
      });
    },
    deleteDrugs(id) {
      deleteDrugsData({ product_id: id }).then(res => {
        if (res.code == 200) {
          this.getWarehouseListData(this.form);
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    getWarehouseListData(data) {
      data.contain_empty = this.check == true ? 1 : 0;
      getWarehouseList(data).then(res => {
        this.tableData = [];
        this.tableData = res.data.data;
        console.log(res.data);
        this.total = res.data.total;
      });
    },
    // 新增药品按钮
    newDrugs() {
      this.$router.push({ name: "newDrugs" });
    },
    //启用禁用
    async changeState(row) {
      console.log(row);
      if (row.state1 == false) {
        const confirm = await this.$confirm("确认禁用该药品吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => err);

        if (confirm !== "confirm") {
          return this.$message.info("已取消");
        }
        /*  this.modifyStateData({ id: row.id.toString(), state: 'Active' }) */
        /* row.state1 = true
          row.state = 'Active'
          console.log(this.valueState) */
      } else {
        const confirm = await this.$confirm("确认启用该药品吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => err);

        if (confirm !== "confirm") {
          return this.$message.info("已取消");
        }
        /*  this.modifyStateData({ id: row.id.toString(), state: 'Unactive' }) */
        /* row.state1 = false
          row.state = 'Unactive' */
      }

      console.log(row.state);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/drugsManagement/drugInformationManagement.scss";
</style>
